package DBLayer;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;

import ModelLayer.TreatmentCategory;

public class DBTreatCat implements IFDBTreatCat {

	private  Connection con;
  
    public DBTreatCat() 
    {
       con = DBConnection.getInstance().getDBcon();
    }
    
    public ArrayList<TreatmentCategory> getTreatCategories()
	{
		return miscWhere("", false);
	}
    
	//miscWhere is used when more than one TreatmentCategory is selected and build
    private ArrayList<TreatmentCategory> miscWhere(String query, boolean retrieveAssociation)
	{
		ResultSet results;
		ArrayList<TreatmentCategory> list = new ArrayList<TreatmentCategory>();
		
		String wQuery =  buildQuery(query);
        System.out.println("DbTreatmentCategory " + wQuery); 
        
  		try 
  		{
	 		Statement stmt = con.createStatement();
	 		stmt.setQueryTimeout(5);
	 		results = stmt.executeQuery(wQuery);

			while(results.next()) {
		     	 TreatmentCategory treatObj = new TreatmentCategory();
			     treatObj = buildTreatCategory(results);	
                 list.add(treatObj);
			}
			
			stmt.close();
		}
	 	catch(Exception e){
	 		System.out.println("Query exception - select TreatmentCategory : "+e);
			e.printStackTrace();
	 	}
		return list;
	}
	
    private String buildQuery(String query)
	{
	    String wQuery = "SELECT ID, Name FROM TreatmentCategory";
		
		if (query.length() > 0)
			wQuery = wQuery + " WHERE " + query;
			
		return wQuery;
	}
    
    private TreatmentCategory buildTreatCategory(ResultSet result)
	{
		TreatmentCategory treatCategory = new TreatmentCategory();
		
		try 
		{
			treatCategory.setId(result.getInt("Id"));
			treatCategory.setName(result.getString("Name"));
		}
		catch(Exception err)
		{	
			
		}
		
		return treatCategory;
	}
}
